package com.banggood.upms.common.util;

import java.math.BigInteger;
import java.security.MessageDigest;

/**
 *deprecated
 * @author XuChuangFeng
 * @date 2017/11/6
 */
public class MessageDigest5Util {

    /**
     * MD5加密
     * @param s
     * @return 返回加密过后的二进制字节数组
     * @throws Exception
     */
    public static byte[] md5(String s) throws Exception {
        //获取 MessageDigest 对象，参数为 MD5 字符串，表示这是一个 MD5 算法（其他还有 SHA1 算法等）
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        //update(byte[])方法，输入原数据
        //类似StringBuilder对象的append()方法，追加模式，属于一个累计更改的过程
        return md5.digest(s.getBytes("UTF-8"));
    }

    /**
     * MD5加密后转成16进制的字符串
     * @param s
     * @return 16进制字符串
     * @throws Exception
     */
    public static String md5ToHex(String s) throws Exception {
        return bytesToHex3(md5(s));
    }

    private static String bytesToHex1(byte[] md5Array) {
        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < md5Array.length; i++) {
            int temp = 0xff & md5Array[i];
            String hexString = Integer.toHexString(temp);
            if (hexString.length() == 1) {
                //如果是十六进制的0f，默认只显示f，此时要补上0
                strBuilder.append("0").append(hexString);
            } else {
                strBuilder.append(hexString);
            }
        }
        return strBuilder.toString();
    }

    /**
     * 通过java提供的BigInteger 完成byte->HexString
     */
    private static String bytesToHex2(byte[] md5Array) {
        BigInteger bigInt = new BigInteger(1, md5Array);
        return bigInt.toString(16);
    }

    /**
     * 通过位运算 将字节数组到十六进制的转换
     */
    public static String bytesToHex3(byte[] byteArray) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] resultCharArray = new char[byteArray.length * 2];
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }
        return new String(resultCharArray);
    }

    /**
     * 二进制转十六进制
     * @param bytes
     * @return
     */
    public static String bytesToHex4(byte[] bytes) {
        StringBuffer md5str = new StringBuffer();
        // 把数组每一字节换成16进制连成md5字符串
        int digital;
        for (int i = 0; i < bytes.length; i++) {
            digital = bytes[i];

            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        return md5str.toString();
    }
}
